import api from "@/http/api";
import { ADMIN_MENU_FOR_ROLE } from "@/http/uri";
import { asyncRoutes } from "@/router";
import { UNSHOW } from "@/setting";
import { buildTree } from "@/utils";
import { defineStore } from "pinia";

export const useMenuStore = defineStore({
  id: "menu",
  state: () => ({
    menus: [],
    accessMenus: [],
    showMenus: [],
  }),
  getters: {
    getMenus: (state) => state.menus,
  },
  actions: {
    setMenus(data) {
      this.menus = data;
    },
    async generateRoutes(role) {
      return new Promise((resolve, reject) => {
        const menus = [];
        const menusData = {};
        api
          .GET(ADMIN_MENU_FOR_ROLE, { role })
          .then((res) => {
            // 格式化 请求 而来的 路由
            const _menus = [];
            res.data.forEach((item) => {
              menus.push(item["path"]);
              menusData[item["path"]] = item;

              _menus.push({
                meta: {
                  realPath: item["path"],
                  icon: item["icon"],
                  title: item["name"],
                  sort: item["sort"],
                },
                path: item["path"],
                id: item["id"],
                pid: item["pid"],
                hidden: UNSHOW.includes(item["path"]),
              });
            });

            let temp = buildTree(_menus, "id", "pid", (item) => item.pid == 0);

            console.log(
              "%c [ temp ]-47",
              "font-size:13px; background:pink; color:#bf2c9f;",
              temp
            );

            const accessedRoutes = filterAsyncRoutes(
              asyncRoutes,
              menus,
              menusData
            );

            this.accessMenus = accessedRoutes;
            // this.menusInner = constantRouter.concat(accessedRoutes);
            temp = temp.sort((a, b) => b?.meta?.sort - a?.meta?.sort);
            this.showMenus = temp;
            resolve(accessedRoutes);
          })
          .catch((error) => {
            console.log("[ error ] >", error);
            reject(error);
          });
      });
    },
  },
});

function filterAsyncRoutes(asyncRoutes, menus, menusData) {
  const res = [];
  asyncRoutes.forEach((route) => {
    const tmp = { ...route };
    if (hasPermission(menus, tmp)) {
      menusData[`${route.path}`];
      // 项目 路由名称 和 后台名称 绑定
      tmp.meta.title = menusData[`${route.path}`]?.name ?? tmp.meta.title;
      if (tmp.children) {
        tmp.children = filterAsyncRoutes(tmp.children, menus, menusData);
      }
      res.push(tmp);
    }
  });
  return res;
}

function hasPermission(menus, route) {
  if (route.meta && route.path) {
    return menus.some((role) => role.includes(route.path));
  } else {
    return true;
  }
}
